package com.qyt.hotel.service.impl;

import com.qyt.hotel.dao.CodeMapper;
import com.qyt.hotel.entity.Code;
import com.qyt.hotel.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.WeakHashMap;

@Service
@Transactional
public class CodeServiceImpl implements CodeService {

    @Autowired
    private CodeMapper codeMapper;

    private final WeakHashMap<String, Object> cache = new WeakHashMap<>();

    @Override
    public void saveCode(String token, String code) {
        if (cache.get(token) != null) {
            codeMapper.updateCode(token, code);
            return;
        }

        Code codeEntity = new Code();
        codeEntity.setCode(code);
        codeEntity.setSendTime(new Date());
        codeEntity.setToken(token);
        codeMapper.save(codeEntity);
        cache.put(token, codeEntity);
    }

    @Override
    public boolean validCode(String codeToken, String code) {
        Code codeEntity = codeMapper.valid(code, codeToken);
        return codeEntity != null && System.currentTimeMillis() - codeEntity.getSendTime().getTime() <= 15 * 60 * 1000;
    }
}
